﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using Motorbike.Model;
using WinForm.Validation;
using Motorbike.BLL;

namespace Motorbike.APP.Forms
{
    public partial class UserAddForm : AbsBaseForm
    {
        private User _currentUser;
        private IntegrateValidator validator;

        public User CurrentUser
        {
            set
            {
                this._currentUser = value;
                this.userCode.Text = this._currentUser.Code;
                this.userPassword.Text = this._currentUser.Password;
                this.userName.Text = this._currentUser.Name;
                this.userRole.SelectedItem = ApplicationContext.Instance.GetRoleItem(this._currentUser.RoleId);
            }

            get 
            {
                this._currentUser.Code = userCode.Text.Trim();
                this._currentUser.Password = userPassword.Text;
                this._currentUser.Name = userName.Text.Trim();
                this._currentUser.RoleId = (Role)((KryptonListItem)userRole.SelectedItem).Tag;
                return this._currentUser;
            }
        }

        public UserAddForm()
        {
            InitializeComponent();
            LoadRoles();
            LoadUser();

            validator = WinFormIntegrateValidator.CreateInstance()
                .AddNotBlankFieldValidator(userCode, userPassword, userName, userRole);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LoadUser()
        {
            if (null == this._currentUser)
            {
                this.CurrentUser = User.Create();
            }
        }

        private void LoadRoles()
        {
            ICollection<KryptonListItem> roleItems = ApplicationContext.Instance.GetAllRolItems();
            foreach (KryptonListItem item in roleItems)
            {
                this.userRole.Items.Add(item);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (validator.Validate())
            {
                if (BllServiceFactory.Instance.SystemService.SaveUser(this.CurrentUser))
                {
                    ShowMessage("成功添加用户：" + this.CurrentUser.Name);
                    this.Close();
                }
            }
        }
    }
}
